package com.example.hikiot.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.hikiot.response.DailyStaticsResponse;
import com.example.hikiot.response.HikResponse;
import com.example.hikiot.response.TokenResponse;
import com.example.hikiot.utils.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class HikiApi {

    @Value("${hik.baseurl}")
    String baseUrl;

    @Value("${hik.appkey}")
    String appkey;

    @Value("${hik.appsecret}")
    String appsecret;

    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appKey", appkey);
        jsonObject.put("appSecret", appsecret);

        Request.Builder requestbuilder = new Request.Builder()
                .url(baseUrl + "/auth/exchangeAppToken")
                .post(RequestBody.create(jsonObject.toJSONString(), mediaType));

        Request request = requestbuilder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        HikResponse<TokenResponse> hikResponse = JSONObject.parseObject(response.body().string(), new TypeReference<HikResponse<TokenResponse>>() {
        });
        if (hikResponse.getCode() == 0) {
            return hikResponse.getData().getAppAccessToken();
        }
        return "";
    }

    public List<DailyStaticsResponse> getDailyStatics(String beginDate, String endDate) throws Exception {

        List<DailyStaticsResponse> retList = new ArrayList<>();

        boolean hasNext = true;
        int page = 1;
        int size = 1000;
        while (hasNext) {

            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("beginDate", beginDate);
            jsonObject.put("endDate", endDate);
            jsonObject.put("page", page);
            jsonObject.put("size", size);

            String encryedData = RSAUtils.encryptByPrivateKey(jsonObject.toJSONString(), appsecret);

            JSONObject bodySecret = new JSONObject();
            bodySecret.put("bodySecret", encryedData);

            Request.Builder requestbuilder = new Request.Builder()
                    .addHeader("App-Access-Token", getAccessToken())
                    .addHeader("Content-Type", "application/json")
                    .url(baseUrl + "/attendance/v1/dailyStatics/page")
                    .post(RequestBody.create(bodySecret.toJSONString(), mediaType));

            Request request = requestbuilder.build();
            OkHttpClient okHttpClient = new OkHttpClient();
            Response response = okHttpClient.newCall(request).execute();
            HikResponse<String> hikResponse = JSONObject.parseObject(response.body().string(), new TypeReference<HikResponse<String>>() {
            });
            if (hikResponse.getCode() != 0) {
                log.error("获取考勤接口失败", hikResponse.getCode());
                continue;
            }

            DailyStaticsResponse[] dailyStaticsResponses = JSONObject.parseObject(RSAUtils.decryptByPrivateKey(hikResponse.getData(), appsecret), new TypeReference<DailyStaticsResponse[]>() {
            });

            if (dailyStaticsResponses.length < 1) {
                hasNext = false;
            }

            retList.addAll(Arrays.asList(dailyStaticsResponses));
            page++;
        }

        return retList;
    }
}
